const deptTmpl = require("./tmpl/build/template");
const _ = require("lodash");
const NProgress = require("nprogress");

require("./sass/style.scss");

import getPageHeader from "../../components/page_header/header.js";
import CollapseList from "../../components/collapse_list/index.js";
import ImagePlugin from "../../components/imagePlugin/image.js";
import {getDepts, delDept} from "../dao.js";
import Validator from "../../components/formValidator/validator.js";
import waitMe from "../../components/waitMe/index.js";
import confirmModal from "../../components/confirmModal/modal.js";


class Department {
    constructor (dom, id) {
        this.container = dom;
        this.data = null;
        this.club_id = id;
        this.images = {};
        this.init();
    }

    initThirdComponenets () {
        getPageHeader(this.club_id, false).render("[data-page-header]");
        this.initDeptList(this.data);
    }

    initDeptList (depts) {
        var that = this;
        var config = {
            data: ((depts)=>{
                var result = [];
                _.forEach(depts, (d)=>{
                    result.push({
                        title: d.name,
                        body: deptTmpl("department", d),
                        id: "club-dept-" + d.id
                    });
                    this.images["club-dept-" + d.id] = {
                        src: d.image,
                        is_upload: false
                    };
                });
                result.push({
                    title: "添加部门",
                    body: deptTmpl("department", {
                        is_submit: true
                    }),
                    id: "new-dept",
                    delete: false
                });
                this.images["new-dept"] = {
                    src: "",
                    is_upload: true,
                    url: "web/club/putDept/",
                    eventHandler: {
                        upload: function(formData){
                            if(!that.validateDept("#new-dept")){
                                return false;
                            }
                            waitMe.show();
                            var name = $("#new-dept").find("[data-dept-name]").val();
                            var url = $("#new-dept").find("[data-dept-url]").val();
                            var introduction = $("#new-dept").find("[data-dept-introduction]").val();
                            formData.append("name", name);
                            formData.append("url", url);
                            formData.append("introduction", introduction);
                            formData.append("club_id", that.club_id);
                            return true;
                        },
                        success: function(res) {
                            that.deptList.unshift({
                                title: res.data.name,
                                body: deptTmpl("department", res.data),
                                id: "club-dept-" + res.data.id
                            });
                            that.images["club-dept-" + res.data.id] = {
                                imgObj: new ImagePlugin({
                                    container: "#club-dept-" + res.data.id + " [data-dept-image]",
                                    height: "",
                                    width: "100%",
                                    src: res.data.image,
                                    is_upload: false,
                                })
                            };

                            that.images["new-dept"].imgObj.clearSrc();
                            $("#new-dept").find("[data-dept-name]").val("");
                            $("#new-dept").find("[data-dept-url]").val("");
                            $("#new-dept").find("[data-dept-introduction]").val("");
                            that.deptList.hide("new-dept");

                            waitMe.hide();
                        },
                        fail: function(){
                            waitMe.hide();
                        }
                    }
                };
                return result;
            })(depts),
            container: this.container + " [data-club-depts]",
            collapseId: "club-dept",
            eventHandler: {
                click: function(){
                    var args = Array.prototype.slice.apply(arguments);
                    var collapseList = args.shift();
                    var event = args.shift();
                    var target = event.target;
                    if($(target).data("action") === "save-dept"){
                        that.images["new-dept"].imgObj.upload();
                    }
                },
                delete: function(){

                    var args = Array.prototype.slice.apply(arguments);
                    
                    confirmModal.show(function(){
                        waitMe.show();
                        var collapseList = args.shift();
                        var event = args.shift();
                        var target = event.target;
                        var dept_id = $(target).find("[data-dept-id]").data("dept-id");
                        delDept(that.club_id, dept_id).then(function(res){     
                            collapseList.delete("club-dept-" + dept_id);
                            delete that.images["club-dept-" + dept_id];
                            waitMe.hide();
                        }).catch(function(err){
                            console.error(err);
                            waitMe.hide();
                        });
                    });
                }
            }
        };
        this.deptList = new CollapseList(config);

        // render img
        _.forOwn(this.images, (image, key)=>{
            this.images[key].imgObj = new ImagePlugin({
                container: "#" + key + " [data-dept-image]",
                height: "",
                width: "100%",
                src: image.src,
                is_upload: image.is_upload,
                url: image.url,
                eventHandler: image.eventHandler
            });
        });
    }

    validateDept (dom) {
        $(dom).find(".has-error").removeClass("has-error");
        $(dom).find(".glyphicon-remove").removeClass("glyphicon-remove");
        $(dom).find("[data-toggle=tooltip]").tooltip("destroy").attr("title", "");

        var $name = $(dom).find("[data-dept-name]");
        var $url = $(dom).find("[data-dept-url]");
        var $introduction = $(dom).find("[data-dept-introduction]");

        var validator = new Validator();

        validator.add($name, [{
            strategy: "isNonEmpty"
        }, {
            strategy: "maxLength:20"
        }]);
        validator.add($introduction, [{
            strategy: "isNonEmpty"
        }]);
        if($url.val()){
            validator.add($url, [{
                strategy: "isUrl"
            }]);
        }

        var result = validator.start();
        if(result && result.errorMsg){
            // show the tips and focus
            let $errorField = $(result.dom), top;
            $errorField.attr("title", result.errorMsg).tooltip("show");
            $errorField.closest(".form-group").removeClass("has-error").addClass("has-error");
            $errorField.siblings(".glyphicon").removeClass("glyphicon-remove").addClass("glyphicon-remove");
            top = $errorField.offset().top;
            $("body").scrollTop( top - 60 > 0 ? top - 60 : top);
            return false;
        }else{
            return true;
        }
    }
    

    init () {
        NProgress.start();
        getDepts(this.club_id).then((data)=>{
            this.data = data;
            this.render();
            NProgress.done();
        }).catch((err)=>{
            console.error(err);
            NProgress.done();
        });
    }

    render () {
        var html = deptTmpl("overview", {});
        $(this.container).html(html);
        this.initThirdComponenets();
    }

    deconstructor (){
    }
}

export default Department;